package com.wn.servlet;

import com.alibaba.fastjson.JSON;
import com.wn.bean.Stu;
import com.wn.utils.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 */
@WebServlet("/stu/query")
public class StuQueryServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //回写的数据设置 编码格式
        resp.setContentType("text/html;charset=utf-8");

        //处理请求
        //查询数据中的数据
        Connection conn = JdbcUtil.getConnection();
        //02  准备sql
        String sql = "select * from stu";
        System.out.println("sql = " + sql);
        //03 拿到ps
        PreparedStatement ps = null;

        ResultSet rs = null;
        List<Stu> list = new ArrayList<>();
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                Stu stu = new Stu();
                stu.setId(rs.getInt("id"));
                stu.setName(rs.getString("name"));
                stu.setAge(rs.getInt("age"));

                list.add(stu);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //使用json框架 可以直接把java对象转成 json 字符串
        String jsonString = JSON.toJSONString(list);
        resp.getWriter().write(jsonString);
    }
}
